package cn.edu.sjtu.se.dslab.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sun.jmx.snmp.Timestamp;

import cn.edu.sjtu.se.dslab.action.bean.PageBean;
import cn.edu.sjtu.se.dslab.component.design.DesignPattern;
import cn.edu.sjtu.se.dslab.component.design.DesignPatternType;
import cn.edu.sjtu.se.dslab.dao.IDesignPatternDao;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.service.IDesignPatternService;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.MD5;

/**
 * 
 * @author longshaohang
 * 
 */
@Service("designPatternService")
@Transactional
public class DesignPatternServiceImpl implements IDesignPatternService {

	@Resource(name="designPatternDao")
	private IDesignPatternDao designPatternDao;

	@Override
	public boolean addDesignPattern(DesignPattern designPattern) {
		designPattern.setCreateTime(new Date());
		MD5 md5 = new MD5();
		String uri = null;
		do{
			StringBuffer s = new StringBuffer();
			s.append(designPattern.getName());
			System.out.println(new Timestamp().toString());
			s.append(new Timestamp().toString());
			uri = md5.getMD5ofStr(s.toString()).substring(0, 8);
		}while(!designPatternDao.checkUri(uri));

		designPattern.setUri(Const.URI_DESIGN_PATTERN+":"+uri);
		designPatternDao.save(designPattern);
		return true;
	}

	@Override
	public DesignPattern updateDesignPattern(DesignPattern designPattern) {
		return designPatternDao.update(designPattern);
	}

	@Override
	public DesignPattern getDesignPatternById(long id) {
		return designPatternDao.queryById(id);
	}

	@Override
	public DesignPattern getDesignPatternByName(String name) {
		return designPatternDao.queryByName(name);
	}

	@Override
	public PageBean getPageBean(int pageNum) throws DBException{
		return designPatternDao.queryByPageNum(pageNum);
	}

	@Override
	public List<DesignPattern> getDesignPatternList() {
		return designPatternDao.queryByList();
	}

	@Override
	public DesignPattern getDesignPatternByUri(String uri) {
		return designPatternDao.queryByUri(uri);
	}

	@Override
	public DesignPattern getDesignPatternByType(DesignPatternType type) {
		//在数据库查询的时候，实际是用枚举类型的值来查询，即1,2,3,4,而不是用字符串来匹配的。
		return designPatternDao.queryByType(String.valueOf(type.ordinal()));
	}

}
